package com.tangdi.production.mpaychl.controller;

import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.tangdi.production.mpbase.util.MapUtils;
import com.tangdi.production.tdbase.util.MD5Util;

public class BaseController {

	/**
	 * 返回成功
	 * 
	 * @param response
	 * @param obj
	 * @throws Exception
	 */
	public void returnSuccess(HttpServletResponse response) throws Exception {
		respContent(response, "success");
	}

	/**
	 * 返回失败
	 * 
	 * @param response
	 * @param obj
	 * @throws Exception
	 */
	public void returnFailure(HttpServletResponse response) throws Exception {
		respContent(response, "failure");
	}

	public void respContent(HttpServletResponse response, String content)
			throws Exception {
		PrintWriter out = response.getWriter();
		out.write(content);
		out.flush();
		out.close();
	}
	
    /**
     * 从请求中获取所有的请求参数
     * 
     * @param request
     * @return
     */
    protected Map<String, String> getRequestParams(HttpServletRequest request) {
        Map<String, String> params = new TreeMap<String, String>();
        Enumeration<String> names = request.getParameterNames();
        
        while (names.hasMoreElements()) {
            String name = names.nextElement();
            String value = request.getParameter(name);
            
            params.put(name, value);
        }
        
        return params;
    }
  
    /**
     * 从请求中获取所有的请求参数
     * 
     * @param request
     * @return
     */
    protected Map<String, Object> getRequestParamsV2(HttpServletRequest request) {
        Map<String, Object> params = new TreeMap<String, Object>();
        Enumeration<String> names = request.getParameterNames();
        
        while (names.hasMoreElements()) {
            String name = names.nextElement();
            String value = request.getParameter(name);
            
            params.put(name, value);
        }
        
        return params;
    }
    
	protected static String sign(Map<String, Object> paramMap, String signKey) {
		String signStr = MapUtils.getSignStrByTreeMap(paramMap, true);
		signStr += "&key=" + signKey;
		// String signValue = MD5.encryption(signStr).toUpperCase();
		
		System.out.println("signStr:");
		String signValue = MD5Util.digest(signStr).toLowerCase();
		return signValue;
	}
}
